package cn.lg.soar.cloud.core.config;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.IpUtil;
import cn.lg.soar.core.handler.ex.ErrorResult;
import cn.lg.soar.core.handler.ex.SoarExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.FeignException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * 全局拦截异常处理异常
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Slf4j(topic = "CloudExceptionHandler")
@RestControllerAdvice
public class CloudExceptionHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @ExceptionHandler(value = Exception.class)
    public HttpResult<?> handle(Exception e, HttpServletRequest request, HttpServletResponse response) {
        ErrorResult result = SoarExceptionHandler.handle(e, msg -> {
            log.warn("{} >>> {} >>> {}",
                    IpUtil.getRemoteIp(request),
                    request.getServletPath(),
                    msg
            );
        });
        response.setStatus(result.getStatus());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return result.getResult();
    }

    /*@ExceptionHandler(FeignException.class)
    public HttpResult<?> handleGlobalException(FeignException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setStatus(e.status());
        if (e.responseBody().isPresent()) {
            HttpResult<?> res = objectMapper.readValue(e.responseBody().get().array(), HttpResult.class);
            log.error("远程调用异常，响应信息={}", res.getMsg(), e);
            return res;
        }
        log.error("远程调用异常", e);
        return HttpResult.fail("B0001", e.getLocalizedMessage());
    }*/

    public static void init() {}
}
